//
//  DisplayService.m
//  Menu
//
//  Created by trimad on 11-11-17.
//  Copyright 2011 Trimad Group. All rights reserved.
//

#import "DisplayService.h"

#import "JSON.h"

#import "PageDisplay.h"
#import "Util.h"

@interface DisplayService(Private)

- (NSString *)getPagesJsonDataFromService;
- (NSArray *)getPagesFromService;

@end

@implementation DisplayService

@synthesize pages;

static DisplayService *_instance = nil;

+ (DisplayService *)instance {
	if (!_instance) {
		@synchronized(self) {
			if (!_instance) {
				_instance = [[DisplayService alloc] init];
			}
		}
	}
	return _instance;
}

- (id)init {
	self = [super init];
	pages = [self getPagesFromService];
	return self;
}

- (NSString *)getPagesJsonDataFromService {
	//NSLog(@"getPagesJsonDataFromService");
	NSString* tempStr = [Util readFileForString:@"localPagesJsonData"];
	if (tempStr != nil) {
		return tempStr;
	} else {
		return [Util readResourceForString:@"getInitPages.jsp"];
//		NSString* urlString = [[Util getServiceHost] stringByAppendingString:[[NSString alloc] initWithString:@"getInitPages.jsp"]];
//		tempStr = [Util getResponseByURL:urlString];
//		[Util writeFileForString:tempStr :@"localPagesJsonData"];
//		return tempStr;
	}
}

- (NSArray *)getPagesFromService {
	//NSLog(@"getPagesFromService");
	NSMutableArray *pageArray = [[NSMutableArray alloc] init];
	NSString* tempStr = [self getPagesJsonDataFromService];
	NSArray *formatString = (NSArray *)[tempStr JSONValue];
	for (id category in formatString) {
		NSDictionary *tempDic1 = (NSDictionary *)category;
		PageDisplay *tempPageDisplay = [[PageDisplay alloc] init];
		tempPageDisplay.viewType = [[tempDic1 objectForKey:@"viewType"] intValue];
		tempPageDisplay.itemCodes = [tempDic1 objectForKey:@"itemCodes"];
		
		[pageArray addObject:tempPageDisplay];
	}
	//NSLog(@"pages: %@",pages);
	return pageArray;
}

- (void)dealloc {
	[pages release];
	[super dealloc];
}

@end
